import logging

from apps.settingApi.api.timerTask.apiList.const import APIJSONDATA
from apps.settingApi.api.timerTask.model import timerTaskModel, timerTaskLogModel, timerTaskConfigModel
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from comm.dbConnect import get_yun_session


timerTaskViewModel = timerTaskModel

timerTaskLogViewModel = timerTaskLogModel

# 查询全部任务
def taskInfo():
    logging.info('获取定时任务')
    db = get_yun_session()
    timerTaskList = []
    try:
        timerTaskModelList = db.query(timerTaskViewModel).filter(timerTaskViewModel.status==True).all()
    except:
        db.close()
        return timerTaskList
    for itmTask in timerTaskModelList:
        itmTaskData = {}
        itmTaskData["id"] = itmTask.id
        itmTaskData["name"] = itmTask.name
        itmTaskData["type"] = itmTask.type
        itmTaskData["code"] = itmTask.code
        itmTaskData["code_def"] = itmTask.code_def
        itmTaskData["sort"] = itmTask.sort
        itmTaskData["order_type"] = itmTask.order_type
        itmTaskData["status"] = itmTask.status
        itmTaskData["create_time"] = itmTask.create_time
        itmTaskData["update_time"] = itmTask.update_time
        itmTaskData["rem"] = itmTask.rem
        # 执行任务
        APIJSONDATA.get(itmTask.code,APIJSONDATA['defaultApi'])(db,itmTaskData)

    timerTaskConfig = db.query(timerTaskConfigModel).filter(timerTaskConfigModel.status == True).first()
    if timerTaskConfig is None:
        seconds = 10
    else:
        seconds = timerTaskConfig.time
    return seconds

# 增加日志
def addTimerTaskLog(name,rem):
    db = get_yun_session()
    addData = {}
    addData['id'] = caseGetPrimaryKeyData()
    addData['name'] = name
    addData['rem'] = rem
    try:
        db.add(timerTaskLogViewModel(**addData))
        db.commit()
    except:
        db.close()
        return
    return
